package com.meng.function.tpm.p.small;

import com.google.gson.JsonObject;
import com.meng.function.http.TpmPHttp;
import com.meng.function.tpm.p.pojo.AddressPojo;
import com.meng.function.tpm.p.util.Local;
import com.meng.util.Dict;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;

public class TpmPShareAdd{
    public boolean onCommand(@NotNull CommandSender sender, String userName,String addressName) {
        try{
            Player player = Bukkit.getPlayer(sender.getName());
            List<HashMap<String, Object>> allAddress = new Local().getAllAddress(userName);
            for (HashMap<String, Object> address : allAddress) {
                String addressNamePlayer =  (String) address.get("addressName");
                if (addressNamePlayer.equals(addressName)){
                    if (address.get("isShare").equals("all") || address.get("isShare").equals(player.getName())){
                        localAdd(addressName,
                                (String) address.get("worldName"),
                                (double) address.get("x"),
                                (double) address.get("y"),
                                (double) address.get("z"),
                                player);
                        if (Dict.ADDRESS_SERVER) serverAdd(addressName,(String) address.get("worldName"),
                                (double) address.get("x"),
                                (double) address.get("y"),
                                (double) address.get("z"),
                                player);
                    }else{
                        player.sendMessage("失败，该玩家未将位置分享给您");
                    }
                    break;
                }
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("执行了第二个地方的false");
            return false;
        }
    }

    private void localAdd(String arg, String worldName, double x, double y, double z, Player player) {
        AddressPojo addressPojo = new AddressPojo(arg, worldName, x, y, z);
        if (new Local().addAddress(addressPojo, player.getName())) {
            player.sendMessage("添加成功");
        } else {
            player.sendMessage("失败，添加重复，请删除地址再经行添加");
        }
    }

    private void serverAdd(String arg, String worldName, double x, double y, double z, Player player) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("userName", player.getName());
        jsonObject.addProperty("worldName", worldName);
        jsonObject.addProperty("x", x);
        jsonObject.addProperty("y", y);
        jsonObject.addProperty("z", z);
        jsonObject.addProperty("addressName", arg);
        new TpmPHttp(jsonObject, Dict.IP, "address/add", player, 102).start();
    }
}
